// workers/chat.js

// 使用您的实际API Key替换这里
const API_KEY = 'iDXigR3SggU7WhfS1NWSCj3A6pLdkeLp'; 

worker.onMessage(function(res) {
    let messages;
    
    try {
        // 尝试解析传入的消息，可能是上下文数组或单一文本
        const data = res.data;
        messages = typeof data === 'string' ? JSON.parse(data) : data;
        
        // 如果是单一字符串而不是消息数组，则转换为标准格式
        if (!Array.isArray(messages)) {
            messages = [{role: "user", content: messages}];
        }
    } catch (error) {
        // 解析失败，将输入视为单个用户消息
        messages = [{role: "user", content: res.data}];
    }

    worker.request({
        url: 'https://api.lkeap.cloud.tencent.com/v1/chat/completions',
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${API_KEY.trim()}`, // 确保API Key没有多余的空格
            'Content-Type': 'application/json'
        },
        data: JSON.stringify({
            model: "deepseek-v3",
            messages: messages
        }),
        success: function(response) {
            try {
                const responseData = JSON.parse(response.data);
                if (responseData.choices && responseData.choices[0].message) {
                    worker.postMessage({
                        type: 'success',
                        content: responseData.choices[0].message.content
                    });
                } else {
                    worker.postMessage({
                        type: 'error',
                        content: '返回数据结构异常'
                    });
                }
            } catch (error) {
                worker.postMessage({
                    type: 'error',
                    content: '解析响应数据失败'
                });
            }
        },
        fail: function(error) {
            // 添加更详细的错误信息
            let errorMessage = error.errMsg || '请求失败';
            if (error.statusCode === 401) {
                errorMessage = 'API认证失败，请检查API Key是否正确';
            }
            worker.postMessage({
                type: 'error',
                content: errorMessage
            });
        }
    });
}); 